using System;
using System.Threading;
using System.Threading.Tasks;
using RTMP.SimpleClient;
using RTMP.SimpleClient.Messages;
using RTMP.SimpleClient.Callbacks;

namespace RTMP.SimpleClient.Examples
{
    /// <summary>
    /// 演示基于回调的CreateStream操作
    /// </summary>
    public class CallbackCreateStreamExample
    {
        public static async Task RunExample()
        {
            Console.WriteLine("=== 基于回调的CreateStream示例 ===");

            var client = new RTMPSimpleClient();

            try
            {
                // 连接到RTMP服务器
                await client.ConnectAsync("rtmp://182.254.168.213:1935/live");
                Console.WriteLine("已连接到RTMP服务器");

                // 方式1: 使用回调方式
                Console.WriteLine("\n--- 方式1: 使用回调形式的CreateStreamAsync ---");
                await DemonstrateCallbackStyle(client);

                await Task.Delay(1000);

                // 方式2: 使用传统返回值方式（兼容性）
                Console.WriteLine("\n--- 方式2: 使用传统返回值形式的CreateStreamAsync ---");
                await DemonstrateTraditionalStyle(client);

                await Task.Delay(1000);

                // 方式3: 并发创建多个流
                Console.WriteLine("\n--- 方式3: 并发创建多个流 ---");
                await DemonstrateConcurrentStreams(client);

                // 等待一段时间来接收所有响应
                await Task.Delay(3000);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"示例执行时发生错误: {ex.Message}");
            }
            finally
            {
                try
                {
                    await client.CloseAsync();
                    Console.WriteLine("\n已断开RTMP连接");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"关闭连接时发生错误: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 演示回调风格的CreateStream
        /// </summary>
        private static async Task DemonstrateCallbackStyle(RTMPSimpleClient client)
        {
            var completionTcs = new TaskCompletionSource<bool>();

            await client.CreateStreamAsync(
                onSuccess: streamId =>
                {
                    Console.WriteLine($"✅ 回调方式: 成功创建流, StreamID = {streamId}");
                    completionTcs.TrySetResult(true);
                },
                onError: errorMessage =>
                {
                    Console.WriteLine($"❌ 回调方式: 创建流失败 - {errorMessage}");
                    completionTcs.TrySetResult(false);
                }
            );

            // 等待回调完成
            await completionTcs.Task;
        }

        /// <summary>
        /// 演示传统风格的CreateStream
        /// </summary>
        private static async Task DemonstrateTraditionalStyle(RTMPSimpleClient client)
        {
            try
            {
                var streamId = await client.CreateStreamAsync();
                Console.WriteLine($"✅ 传统方式: 成功创建流, StreamID = {streamId}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 传统方式: 创建流失败 - {ex.Message}");
            }
        }

        /// <summary>
        /// 演示并发创建多个流
        /// </summary>
        private static async Task DemonstrateConcurrentStreams(RTMPSimpleClient client)
        {
            const int streamCount = 3;
            var completedCount = 0;
            var lockObject = new object();
            var allCompletedTcs = new TaskCompletionSource<bool>();

            Console.WriteLine($"开始并发创建 {streamCount} 个流...");

            for (int i = 0; i < streamCount; i++)
            {
                var streamIndex = i + 1;
                
                // 异步创建流，不等待完成
                _ = Task.Run(async () =>
                {
                    await client.CreateStreamAsync(
                        onSuccess: streamId =>
                        {
                            Console.WriteLine($"✅ 流 #{streamIndex}: 成功创建, StreamID = {streamId}");
                            
                            lock (lockObject)
                            {
                                completedCount++;
                                if (completedCount == streamCount)
                                {
                                    allCompletedTcs.TrySetResult(true);
                                }
                            }
                        },
                        onError: errorMessage =>
                        {
                            Console.WriteLine($"❌ 流 #{streamIndex}: 创建失败 - {errorMessage}");
                            
                            lock (lockObject)
                            {
                                completedCount++;
                                if (completedCount == streamCount)
                                {
                                    allCompletedTcs.TrySetResult(false);
                                }
                            }
                        }
                    );
                });
            }

            // 等待所有流创建完成
            await allCompletedTcs.Task;
            Console.WriteLine($"所有 {streamCount} 个流的创建操作都已完成");
        }
    }

    /// <summary>
    /// 高级CreateStream使用示例
    /// </summary>
    public class AdvancedCreateStreamExample
    {
        public static async Task RunAdvancedExample()
        {
            Console.WriteLine("=== 高级CreateStream用法示例 ===");

            var client = new RTMPSimpleClient();

            try
            {
                await client.ConnectAsync("rtmp://182.254.168.213:1935/live");
                Console.WriteLine("已连接到RTMP服务器");

                // 自定义超时和重试逻辑
                await DemonstrateRetryLogic(client);

                await Task.Delay(2000);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"高级示例执行时发生错误: {ex.Message}");
            }
            finally
            {
                try
                {
                    await client.CloseAsync();
                    Console.WriteLine("\n已断开RTMP连接");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"关闭连接时发生错误: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 演示带重试逻辑的CreateStream
        /// </summary>
        private static async Task DemonstrateRetryLogic(RTMPSimpleClient client)
        {
            const int maxRetries = 3;
            int attempt = 0;
            bool success = false;

            while (attempt < maxRetries && !success)
            {
                attempt++;
                Console.WriteLine($"\n尝试创建流 (第 {attempt} 次)...");

                var attemptTcs = new TaskCompletionSource<bool>();

                await client.CreateStreamAsync(
                    onSuccess: streamId =>
                    {
                        Console.WriteLine($"✅ 成功创建流 (第 {attempt} 次尝试), StreamID = {streamId}");
                        success = true;
                        attemptTcs.SetResult(true);
                    },
                    onError: errorMessage =>
                    {
                        Console.WriteLine($"❌ 第 {attempt} 次尝试失败: {errorMessage}");
                        if (attempt >= maxRetries)
                        {
                            Console.WriteLine($"已达到最大重试次数 ({maxRetries})，停止重试");
                        }
                        else
                        {
                            Console.WriteLine("将在1秒后重试...");
                        }
                        attemptTcs.SetResult(false);
                    }
                );

                await attemptTcs.Task;

                if (!success && attempt < maxRetries)
                {
                    await Task.Delay(1000); // 重试前等待1秒
                }
            }

            if (success)
            {
                Console.WriteLine("🎉 最终成功创建流!");
            }
            else
            {
                Console.WriteLine("😞 所有重试均失败");
            }
        }
    }
}